package com.peng.leetcode.list;

/**
 * SwapPairs
 * 24. 两两交换链表中的节点
 * https://leetcode.cn/problems/swap-nodes-in-pairs/
 *
 * @author: lupeng6
 * @create: 2023/2/14 12:34
 */
public class SwapPairs {
    public ListNode swapPairs(ListNode head) {
        return reverseGroup(head, 2);
    }

    private ListNode reverseGroup(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        ListNode curr = head;
        for (int i = 0; i < k; i++) {
            if (curr == null) {
                return head;
            }
            curr = curr.next;
        }
        ListNode newHead = reverse(head, curr);
        head.next = reverseGroup(curr, k);
        return newHead;
    }

    private ListNode reverse(ListNode head, ListNode tail) {
        ListNode prev = null;
        while (head != tail) {
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }
}
